//
//  SSOAuthController.swift
//  SSSina
//
//  Created by ss on 2017/7/1.
//  Copyright © 2017年 ss. All rights reserved.
//

import UIKit

class SSOAuthController: UIViewController {

    
    //利用loadView 把webView设置成view
    override func loadView() {
        view = webView
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        view.backgroundColor = UIColor.white
    }
    
    //设置视图
    private func setupUI() {
        view.backgroundColor = UIColor.white
        setupNav()
    }
    //设置导航
    
    private func setupNav(){
        
        //设置登陆
        navigationItem.title = "微博登陆"
        //左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: nil, title: "取消", target: self, action: #selector(cancelBtnClick))
        //右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: nil, title: "自动登陆", target: self, action: #selector(autoLoginBtnClick))
    }
    
    //取消按钮点击事件
    @objc private func cancelBtnClick() {
        dismiss(animated: true, completion: nil)
    }
    
    //自动登陆按钮点击事件
    @objc private func autoLoginBtnClick(){
        //js字符串
        let jsstring = "document.getElementById('userId').value='\(SSWEIBONAME)';document.getElementById('passwd').value='\(SSWEIBOPASSWORD)'"
        //js 注入
        webView.stringByEvaluatingJavaScript(from: jsstring)
    }
    
    //懒加载控件webview
    
    //https://api.weibo.com/oauth2/authorize
    private lazy var webView:UIWebView = {
       let webView = UIWebView()
        //设置webView 代理
        webView.delegate = self
        //urlString url地址与请求参数字符串拼接
       let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(SSAppKey)&redirect_uri=\(SSREDIRECT_URI)"
       //print(urlString)
        //字符串得到url
        let url = URL(string: urlString)
        
        //判断url是否为nil
        guard let u = url else{
            return webView
        }
        webView.loadRequest(URLRequest(url:u))
        return webView
    }()

}

//遵守webView 代理协议
extension SSOAuthController:UIWebViewDelegate{
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
    }
    //监听webView将要加载的request 默认不实现返回为true,也就是同意当前webview加载当前界面
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //通过request 得到对应的urlstring ->得到absoluteString
        let urlString = request.url?.absoluteString
        
        //判断urlString是否为nil 而且是之前你预留的回调页\
        //判断字符串的前缀 hasPrefix hasSuffix后缀
        
        if let u = urlString,u.hasPrefix(SSREDIRECT_URI) {
            //获取地址的请求参数部分 判断是否为nil
            if let query =  request.url?.query{
                //得到code 从当前字符串,到最后
                let code = query.substring(from: "code=".endIndex)
                print("终于拿到了",code)
                
                SSOAuthViewModel.share.getUserAccount(code: code, finish: { (isFinish) in
                    //如果false,代表请求失败
                    if !isFinish{
                        print("请求失败")
                    }else{
                        print("请求成功")
                        //关闭控制器
                        self.dismiss(animated: false, completion: { 
                            NotificationCenter.default.post(name: SSSWITCHROOTVIEWCONTROLLER, object: nil)

                        })
                    }
                })
            }
        }
        
        return true 
    }
}


